using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Yz.Base.Constants;
using Yz.Base.Dal;
using Yz.Model.Config;
using Yz.Model.Dal;
using Yz.Mvc.Filters;
using Yz.Mvc.Modules;

namespace Yz.Manage
{
    public class Startup
    {
        public IConfiguration _configuration { get; }
        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<YzContext>(options => options.UseSqlServer(_configuration.GetConnectionString(DbConstant.YzContext), p => p.MigrationsAssembly(DbConstant.SqlServerMigration)));
            services.AddControllersWithViews(options => options.Filters.Add(new ExceptionAttribute())).AddControllersAsServices();
            services.Configure<CacheConfig>(_configuration.GetSection(ConfigConstant.CacheConfig));
            services.Configure<WebConfig>(_configuration.GetSection(ConfigConstant.WebConfig));
        }
        public void ConfigureContainer(ContainerBuilder containerBuilder)
        { 
            containerBuilder.RegisterModule<AutofacModule>(); 
            var controllerBaseType = typeof(ControllerBase);
            containerBuilder.RegisterAssemblyTypes(typeof(Program).Assembly)
                .Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
                .PropertiesAutowired();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, YzContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            context.Database.Migrate();
        }
    }
}
